package com.pdsu.graduation_design.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pdsu.graduation_design.MainActivity;
import com.pdsu.graduation_design.R;
import com.pdsu.graduation_design.adapter.PayListViewAdapter;
import com.pdsu.graduation_design.component.PayListView;
import com.pdsu.graduation_design.dto.PayCommodityDTO;
import com.pdsu.graduation_design.dto.Store;
import com.pdsu.graduation_design.utils.JsonUtil;
import com.pdsu.graduation_design.utils.Result;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.List;
import java.util.Map;

public class Pay_Fragment extends Fragment  {

    private Button pay_remove_btn;
    private boolean isFirstLoading = true;
    private LinearLayout pay_dynamic_main_ll,pay_dynamic_ll;
    private View currentView;
    private TextView bar_top_textview;
    private CheckBox pre_main_cb;
    private Button buy_now;
    private List<PayCommodityDTO> payCommodityDTOS_to_order;

    private ListView pay_listview;
    private TextView all_price;
    private  Map<Integer,List<PayCommodityDTO>> payCommodityDTOListsMaps_temp ;
    private  List<Store> storesList_temp;
    private Context context;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (MainActivity.storesList ==null||MainActivity.storesList.size()==0){
            currentView=inflater.inflate(R.layout.fragment_pay_empty,null);
        }else {
            this.storesList_temp = MainActivity.storesList;
            this.payCommodityDTOListsMaps_temp=MainActivity.payCommodityDTOListsMaps;
            currentView=inflater.inflate(R.layout.fragment_pay,null);
            init();
            upDateData();
            newOperation();
            allChecked();
            giveMoney();
            remove();
        }
        return currentView;
    }


    private void allChecked(){

        pre_main_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (int ch_num = 1 ; ch_num<pay_dynamic_main_ll.getChildCount();ch_num++){

                    LinearLayout layout_temp = (LinearLayout) pay_dynamic_main_ll.getChildAt(ch_num);

                    CheckBox checkBox_tp=layout_temp.findViewById(R.id.pay_order_allchecked_cb);
                    checkBox_tp.setChecked(isChecked);


                }
            }
        });



    }

   private void upDateData(){
       System.out.println("update");
       System.out.println(MainActivity.storesList.size());
       System.out.println("update");

        MainActivity.initUser();



   }

   private void newOperation(){
       bar_top_textview.setText("购物车");
       List<Store> storesList_temp=MainActivity.storesList;
       Map<Integer, List<PayCommodityDTO>> map2=MainActivity.payCommodityDTOListsMaps;
       System.out.println(map2.size());
       for (Store s:storesList_temp){
           LinearLayout view = (LinearLayout) View.inflate(getContext(),R.layout.fragment_pay_listview_item,null);
           CheckBox pay_order_allchecked_cb =view.findViewById(R.id.pay_order_allchecked_cb);
           TextView storetitle=view.findViewById(R.id.pay_store_title_textview);
           storetitle.setText(s.getUsername());
//           view.findViewById(R.id.pay_listview_itemlistview);
           int num= map2.get(s.getUid()).size();
           for (int i =0;i<num;i++){
               PayCommodityDTO p_temp=map2.get(s.getUid()).get(i);
               LinearLayout view2= (LinearLayout) View.inflate(context,R.layout.fragment_pay_listview_item_listviewitem,null);
               //产品名
               TextView title = view2.findViewById(R.id.fragment_pay_listview_item_listview_commodityName);
               //图片
               Button add_btn,del_btn;
               CheckBox checkBox;
               LinearLayout layout;
               TextView number,com_desc;
               TextView commodity_single_price_tv;
               TextView commodityName;
               ImageView commodityImageView;
               commodity_single_price_tv=view2.findViewById(R.id.fragment_pay_listview_item_listview_commodityprice);
               commodityImageView=view2.findViewById(R.id.fragment_pay_listview_item_listview_commodityimage);
               layout=view2.findViewById(R.id.fragment_pay_listview_item_listview_item_detail);
               checkBox=view2.findViewById(R.id.checkbox_pay);
               com_desc=view2.findViewById(R.id.fragment_pay_listview_item_listview_commoditydesc);
               number=view2.findViewById(R.id.pay_number);
               add_btn=view2.findViewById(R.id.fragment_pay_listview_item_listview_add_btn);
               del_btn=view2.findViewById(R.id.fragment_pay_listview_item_listview_delete_btn);

               com_desc.setText(p_temp.getSell_desc());
               title.setText(p_temp.getCname());
               number.setText(p_temp.getUcnumber()+"");
               commodity_single_price_tv.setText(p_temp.getPrice().toString());
               Picasso.with(context).load(p_temp.getImage()).into(commodityImageView);
               view.addView(view2);
               DecimalFormat df = new DecimalFormat("#.00");
               checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                   @SuppressLint("ResourceAsColor")
                   @Override
                   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                       if (isChecked){
                           p_temp.setBo(true);
                           payCommodityDTOS_to_order.add(p_temp);
                           Double num = Double.valueOf(df.format(Double.valueOf(all_price.getText().toString())));
                           System.out.println(num+"num");
                           Double sum = num + Double.valueOf(df.format(Double.valueOf(p_temp.getPrice()*p_temp.getUcnumber())));
                           all_price.setText( df.format(sum));
                       }else {
                           Double num = Double.valueOf(df.format(Double.valueOf(all_price.getText().toString())));
                           Double sum = num - Double.valueOf(df.format(Double.valueOf(p_temp.getPrice()*p_temp.getUcnumber())));
                           payCommodityDTOS_to_order.remove(p_temp);
                           System.out.println(payCommodityDTOS_to_order.size()+"size");
                           if (sum<=0){
                               all_price.setText("0.00");
                           }else {
                               all_price.setText(df.format(sum));
                           }
                       }


                       if (payCommodityDTOS_to_order.size()>0){
                           pay_remove_btn.setClickable(true);
                       }else {
                           pay_remove_btn.setClickable(false);


                       }
                   }
               });
                add_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num= Integer.parseInt(number.getText().toString());

                        /**
                         * 判断大于库存数量
                         */

                        if ((num+1)>p_temp.getCnumber()){
                            Toast.makeText(context, "库存不足", Toast.LENGTH_SHORT).show();
                        }else {
                            num=num+1;
                            number.setText(num+"");
                            p_temp.setUcnumber(p_temp.getUcnumber()+1);

                            if (checkBox.isChecked()){
                                payCommodityDTOS_to_order.remove(p_temp);
                                payCommodityDTOS_to_order.add(p_temp);
                                Double temp = Double.valueOf(df.format(Double.valueOf(all_price.getText().toString())));
                                temp=temp+p_temp.getPrice();
                                all_price.setText(df.format(temp));
                            }
                        }



                    }
                });
                del_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num= Integer.parseInt(number.getText().toString());

                        if (num==1){
                            Toast.makeText(context, "数量不能小于1个", Toast.LENGTH_SHORT).show();
                        }else {
                            p_temp.setUcnumber(p_temp.getUcnumber()-1);

                            num=num-1;
                            number.setText(num+"");
                            if (checkBox.isChecked()){
                                payCommodityDTOS_to_order.add(p_temp);
                                Double temp = Double.valueOf(df.format(Double.valueOf(all_price.getText().toString())));
                                temp=temp-p_temp.getPrice();
                                all_price.setText(df.format(temp));
                            }
                        }
                    }
                });


           }

           pay_order_allchecked_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
               @Override
               public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                       for (int childnum=1;childnum<=num;childnum++){
                           LinearLayout view3= (LinearLayout) view.getChildAt(childnum);
                           CheckBox checkBox=view3.findViewById(R.id.checkbox_pay);
                           checkBox.setChecked(isChecked);
                       }
               }
           });
           pay_dynamic_main_ll.addView(view);


   }}

    private void init() {
        pay_remove_btn = currentView.findViewById(R.id.pay_remove_tv);
        payCommodityDTOS_to_order=new ArrayList<>();
        buy_now=currentView.findViewById(R.id.buy_now_btn);
        pre_main_cb=currentView.findViewById(R.id.pre_main_cb);
        pay_dynamic_main_ll=currentView.findViewById(R.id.pay_dynamic_main_ll);
        context=getContext();
        bar_top_textview = currentView.findViewById(R.id.bar_top_common_textview);
        pay_listview=currentView.findViewById(R.id.pay_list);
        all_price=currentView.findViewById(R.id.pay_allprice);
        //购买按钮
        buy_now=currentView.findViewById(R.id.buy_now_btn);

    }

    private void giveMoney(){

//      数据  payCommodityDTOS_to_order;
        buy_now.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (payCommodityDTOS_to_order.size()==0){

                        Toast.makeText(context, "请选择商品", Toast.LENGTH_SHORT).show();
                    }else {
                        String json_data=JsonUtil.ListToJson(payCommodityDTOS_to_order);
                        Intent intent=new Intent(context,PayOrderActivity.class);
                        intent.putExtra("json_data_pa",json_data);
                        intent.putExtra("all_price",all_price.getText().toString());
                        intent.putExtra("type_http",1);
                        startActivity(intent);
                    }


                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

            }
        });



    }


    private void remove(){

        pay_remove_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"click",Toast.LENGTH_SHORT).show();
                if (payCommodityDTOS_to_order.size()>0){


                    try {
                        RequestParams requestParams=new RequestParams(MainActivity.URL+"/payCommodity/removePayCommodityByUIDAndCID");
                        String json_data = JsonUtil.ListToJson(payCommodityDTOS_to_order);
                        requestParams.addParameter("list_data",json_data);
                        requestParams.addParameter("uid",MainActivity.user_admin.getUid());
                        x.http().post(requestParams, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String result) {
                                try {
                                    Result r =JsonUtil.JsonToObj(result,Result.class);
                                    if (r.getCode().equals("200")){
                                        Toast.makeText(context,"移除成功",Toast.LENGTH_SHORT).show();
                                        payCommodityDTOS_to_order.clear();
                                        MainActivity.initUser();


                                    }else {
                                        Toast.makeText(context,"移除失败",Toast.LENGTH_SHORT).show();

                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {

                            }

                            @Override
                            public void onCancelled(CancelledException cex) {

                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }


                }
                else {
                    Toast.makeText(context, "请选择要移出的商品", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}
